/**
 * Created by xiewei on 9/15/15.
 */
var dtFmlBackBtn = $('#dtFmlBack');//返回按钮
var dtFmlTelNumText = $("#dtFmlTelNum");//（传入）电话号码
var dtFmlSNSNumText = $("#dtFmlSNSNum");//QQ号或微信号输入框
var dtFmlSNSChange = $("#dtFmlSNSChange");//QQ号或微信号切换按钮
var dtFmlSNSNumUl = dtFmlSNSChange.next();//QQ号、微信号选择下拉框
var dtFmlSNSNumQQ = dtFmlSNSNumUl.children("li:first");//QQ号、微信号选择下拉框
var dtFmlSNSNumWechat = dtFmlSNSNumUl.children("li:last");//QQ号、微信号选择下拉框
var isQQ = 1;//当前是QQ还是微信 1:QQ 0:wechat

var dtFmlNameText = $("#dtFmlName");//寄养家庭名称
var dtFmlRealNameText = $("#dtFmlRealName");//真实姓名
var dtFmlIDCodeText = $("#dtFmlIDCode");//寄养家庭主人身份证号
var dtFmlIDCardIcon = $("#dtFmlIDCardIcon");//身份证照片上传按钮
var dtFmlIDCardFile = $("#dtFmlIDCardFile");//身份证照片上传表单控件（隐藏）
var dtFmlIDCardImg = $("#dtFmlIDCardImg");//身份证照片预览

var dtFmlInterviewTable = $("#dtFmlIntrvwTable");//预约视频认证时间
var dtFmlTreatyCheck = $("#dtFmlTreatyCheck");//寄养协议同意选择控件
var dtFmlTreatyAlink = $("#dtFmlTreaty");//查看寄养家庭服务协议链接

var intrvwSelIframe = $("#interviewFrame");//预约面试时间页面
var intrvwTimeSelIframe = $("#interviewTimeFrame");//预约面试时间选择页面
var intrvwSelPanel = $("#intrvwSelPanel");
var dtFmlDateSpan = $('#dtFmlDateSpan');
var dtFmlTimeSpan = $('#dtFmlTimeSpan');
var intrvwSelBack = intrvwSelPanel.children("a:first");//预约返回按钮
var intrvwSelSubmit = intrvwSelPanel.children("a:last");//预约完成按钮
var treatyBox = $("#treatyBox");//协议
var treatyIframe = $("#treatyIframe");//协议页面
var treatyBackBtn = $("#treatyBackBtn");//关闭协议按钮

var dtFmlSubmitBtn = $("#dtFmlOrderSubmit");//提交预约按钮
//预约面试时间iframe相关
var interview,dtFmlDateSel,intrvwTimeSelIframe,dtFmlTimeSel,selectedDay=null,selectedTime=null;

$(function(){
    //寄养家庭服务协议
    treatyIframe.css({
        top: 0,
        left: 0,
        border: "none",
        width: "100%",
        height: screen.height
    });

    //预约面试时间的加载
    intrvwSelIframe.css({
        top: 50,
        left: 0,
        width: "100%",
        height: 80,
        border: 0
    });
    //面试时间iframe
    intrvwTimeSelIframe.css({
        top: 130,
        left: 0,
        width: "100%",
        height: screen.height-130,
        border: 0
    });
});

//申请寄养家庭信息
var applyFamilyData = {
    idcard: '',
    idcardPic: '',
    interviewDate: '',
    interviewTime: '',
    name: '',
    trueName: '',
    userId: '',
    qq: '',
    wechat: '',
    session: ''
}
//上传图片
var imgData = {
    session: '',
    type: '',
    userId: ''
}
/**
 * 手机号输入期间检查（只允许输入数字）
 */
function check(e){
    var keyCode = e.keyCode || event.keyCode;
    if (keyCode >= 48 && keyCode <= 57) {
        event.returnValue = true;
    }else {
        event.returnValue = false;
    }
}
/**
 * QQ号或微信号码的输入切换
 */
$(document).click(function(){
    dtFmlSNSNumUl.addClass("hidden");
});
var snsNumTypeChange = function(e){
    e.stopPropagation();
    dtFmlSNSNumUl.toggleClass("hidden");
}
var snsNumTypeQQ = function(){
    isQQ = 1;
    dtFmlSNSNumText.attr("placeholder","输入QQ号码");
    dtFmlSNSNumText.attr("onkeypress","check(event)");
    dtFmlSNSNumText.attr("onkeyup","this.value=this.value.replace(/[^0-9]+/g,'')");
    dtFmlSNSNumText.attr("oninput","this.value=this.value.replace(/[^0-9]+/g,'')");

    dtFmlSNSChange.text('QQ');
    dtFmlSNSNumUl.addClass("hidden");
}
var snsNumTypeWechat = function(){
    isQQ = 0;
    dtFmlSNSNumText.attr("placeholder","输入微信号码");
    dtFmlSNSNumText.removeAttr("onkeypress");
    dtFmlSNSNumText.removeAttr("onkeyup");
    dtFmlSNSNumText.removeAttr("oninput");
    dtFmlSNSChange.text('微信');
    dtFmlSNSNumUl.addClass("hidden");
}
/**
 * QQ/微信检查
 */
var snsNumCheck = function(){
    var snsNum = dtFmlSNSNumText.val().trim();
    if(snsNum=="" || snsNum==null){
        showMessageAlert("微信和QQ必填一项，以用于视频认证");
        dtFmlSNSNumText.focus();
        return false;
    }else{
        if(isQQ == 1){
            applyFamilyData.qq = dtFmlSNSNumText.val();
        }else{
            applyFamilyData.wechat = dtFmlSNSNumText.val();
        }
        return true;
    }
}
/**
 * 寄养家庭名称检查
 * @param value
 */
var familyNameCheck = function(){
    var value = dtFmlNameText.val().trim();
    //家庭名称名称为中文、英文、数字
    var reg = /[\u4e00-\u9fa5|a-zA-Z|0-9]/;
    if(value=="" || value==null){
        showMessageAlert("请填写寄养家庭名称");
        dtFmlNameText.focus();
        return false;
    }else if(!reg.test(value)){
        showMessageAlert("寄养家庭名称不可输入特殊符号");
        dtFmlNameText.focus();
        return false;
    }
    applyFamilyData.name = value;
    return true;
}
/**
 * 用户真实姓名检查
 * @param value
 */
var trueNameCheck = function(){
    var value = dtFmlRealNameText.val().trim();
    //用户真实姓名只能是中文和英文
    var reg = /[\u4e00-\u9fa5|a-zA-Z]/;
    if(value=="" || value==null){
        showMessageAlert("请填写真实姓名");
        dtFmlRealNameText.focus();
        return false;
    }else if(!reg.test(value)){
        showMessageAlert("真实姓名不可输入特殊符号");
        dtFmlRealNameText.focus();
        return false;
    }
    applyFamilyData.trueName = value;
    return true;
}
/**
 * 身份证号码验证
 * @param value
 * @returns {boolean}
 */
var idCardCodeCheck = function(){
    var value = dtFmlIDCodeText.val().trim();
    var IDCardReg15 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
    var IDCardReg18 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;;
    if(value=="" || value==null){
        showMessageAlert("请输入身份证号码");
        //dtFmlIDCodeText.focus();
        return false;
    }else if(value.length<15 || !(IDCardReg15.test(value)||IDCardReg18.test(value)) ){
        showMessageAlert("请填写正确的身份证号");
        //dtFmlIDCodeText.focus();
        return false;
    }
    applyFamilyData.idcard = value;
    return true;
}
/**
 * 身份证照片验证
 */
var idCardImgCheck = function(){
    var imgSrc = $('#dtFmlIDCardImg').attr('src');
    if(imgSrc=="" || imgSrc==null){
        showMessageAlert("请上传身份证照片");
        return false;
    }else{
        return true;
    }
}
/**
 * 身份证照片上传 上传后预览效果
 */
window.URL = window.URL || window.webkitURL;
var idCardImgUpdate = function(){
    //图片初始化
    dtFmlIDCardImg = $("#dtFmlIDCardImg");
    var imgHeight = 0,imgWidth = 0;
    var uploadImg = $("<img>");

    var files = dtFmlIDCardFile[0].files;
    if(files.length==0){
        return false;
    }
    if(window.FileReader){
        var reader = new FileReader();
        reader.readAsDataURL(files[0]);
        reader.onload = function(){
            uploadImg.attr("src",this.result);
        }
    }else if(window.URL){
        uploadImg.attr("src",window.URL.createObjectURL(files[0]));
        uploadImg.onload = function(){
            window.URL.revokeObjectURL(this.src);
        }
    }else{//IE
        dtFmlIDCardFile.select();
        dtFmlIDCardFile.blur();
        var fileSrc = document.selection.createRange().text;
        document.selection.empty();
        uploadImg.attr("src",fileSrc);
    }
    //图片大小自适应
    var getImgNaturalSize = function(){
        imgHeight = uploadImg[0].naturalHeight;
        imgWidth = uploadImg[0].naturalWidth;
        if(imgHeight==0 || imgWidth==0){
            window.setTimeout(getImgNaturalSize,100);
        }else{
            applyFamilyData.idcardPic = uploadImg.attr("src");
            var imgParent = dtFmlIDCardImg.parent();
            imgParent.css("display","inline-block");
            //调整图片位置
            var imgScale = imgWidth/imgHeight;
            if(imgScale > 135/119){
                var height = imgHeight*(135/imgWidth);
                uploadImg.css({
                    width: 135,
                    height: height,
                    marginTop: 119/2-height/2,
                    marginLeft: 0
                });
            }else{
                var width = imgWidth*(119/imgHeight);
                uploadImg.css({
                    width: width,
                    height: 119,
                    marginTop: 0,
                    marginLeft: 135/2-width/2
                });
            }
            dtFmlIDCardImg.remove();
            imgParent.append(uploadImg.attr("id","dtFmlIDCardImg"));
        }
    }
    getImgNaturalSize();
}
/**
 * 确定预约面试时间
 */
var intrvwSelConfirm = function(){
    var length = $("td.selected",dtFmlTimeSel).length;
    if(length==0){
        showMessageAlert("请选择视频面试时间");
        return false;
    }else if(length==1){
        intrvwSelIframe.hide();
        intrvwSelPanel.hide();
        startScrolling();
        return true;
    }
}
/**
 * 预约日期与时间段检查
 */
var orderDateAndTime = function(){
    var date = applyFamilyData.interviewDate;
    var time = applyFamilyData.interviewTime;
    if(date==0 || date==null || date==""){
        showMessageAlert("请选择预约认证日期");
        return false;
    }else if(time==0 || time==null || time==""){
        showMessageAlert("请选择预约认证时间段");
        return false;
    }
    return true;
}
/**
 * 是否勾选同意协议
 */
var fosterTreatyCheck = function(){
    var ifChecked = dtFmlTreatyCheck.attr("checked");
    if(ifChecked == "checked"){
        return true;
    }else{
        showMessageAlert("请确定同意《双方寄养服务协议》");
        return false;
    }
}
/**
 * 提交申请
 */
var submitInfoCheck = function(){
    if(!familyNameCheck()){
        return false;
    }else if(!snsNumCheck()){
        return false;
    }else if(!trueNameCheck()){
        return false;
    }else if(!idCardCodeCheck()){
        return false;
    }else if(!idCardImgCheck()){
        return false;
    }else if(!orderDateAndTime()){
        return false;
    }else if(!fosterTreatyCheck()){
        return false;
    }
    //提交图片
    imgData.type = '5';
    var uploadData = paramCoding(imgData);
    $.ajaxFileUpload({
        url:'/dog2/attach/uploadAttach',
        secureuri: false,
        fileElementId: 'dtFmlIDCardFile',//file标签的id
        dataType: 'json',
        data: uploadData,
        success: function (res) {
            if(res.respCode){
                applyFamilyData.idcardPic = res.path;
                var data = paramCoding(applyFamilyData);
                //提交申请信息
                $.ajax({
                    url: "/dog2/appFamily/applyFamily",
                    data: data,
                    type: "POST",
                    dataType: 'json',
                    success: function(res){
                        if(res.respCode==0){
                            showMessageAlert('申请已提交');
                            window.open("apply_success.html", "_self");
                        }else{
                            showMessageAlert('提交失败：'+res.respDesc);
                        }
                    }
                });
            }else{
                showMessageAlert('图片提交失败：'+res.respDesc);
            }
        },
        error: function(){
            showMessageAlert('图片提交出错');
        }
    });
}
var backToFamily = function(){
    window.open("family.html","_self");
}
/**
 * 绑定事件
 */
dtFmlBackBtn.on("click",backToFamily);//返回按钮
dtFmlSNSChange.on("click",snsNumTypeChange);//QQ号或微信号码
dtFmlSNSNumQQ.on("click",snsNumTypeQQ);//切换为QQ
dtFmlSNSNumWechat.on("click",snsNumTypeWechat);//切换为微信
dtFmlIDCodeText.on("blur",idCardCodeCheck);//身份证号码验证
dtFmlIDCardIcon.on("change",idCardImgUpdate);//上传身份证照片功能
//预约视频认证时间
dtFmlInterviewTable.on("click",function(){
    interviewSelect();
    intrvwSelIframe.height = screen.height;
    intrvwSelIframe.show();
    intrvwSelPanel.show();
    intrvwTimeSelIframe.show();
    stopScrolling();
});
intrvwSelBack.on("click",function(){
    intrvwTimeSelIframe.hide();
    intrvwSelIframe.hide();
    intrvwSelPanel.hide();
    startScrolling();
});
intrvwSelSubmit.on("click",intrvwSelConfirm);
//点击查看协议
dtFmlTreatyAlink.on("click",function(){
    treatyBackBtn.show();
    treatyBox.height = screen.height;
    treatyBox.show();
    stopScrolling();
});
treatyBackBtn.on("click",function(){
    treatyBox.hide();
    treatyBackBtn.hide();
    startScrolling();
});
dtFmlSubmitBtn.on("click",submitInfoCheck);//提交寄养家庭申请

/**
 * 日期展示：当前日期+35天
 */
var dateFomat = function(date){
    var year = date.getFullYear();
    var month = date.getMonth()+1;
    month = month < 10? ("0"+month) : month;
    var date = date.getDate();
    date = date < 10? ("0"+date) : date;
    return year+"-"+month+"-"+date;
}
var week = ["周日","周一","周二","周三","周四","周五","周六"];
var displayInterviewDate = function(){
    var today = new Date();
    var dateCount = 36;
    for(var i = 0; i < dateCount; i++){
        var date = new Date();
        date.setDate(today.getDate()+i);
        var dateString = dateFomat(date);
        var li = $("<li>").attr("date",dateString);
        if(i==0){
            li.addClass("selected");
            selectedDay = li;
            applyFamilyData.interviewDate = dateString;
            dtFmlDateSpan.text(dateString);
            $("<p>").text("今天").appendTo(li);
        }else if(i==1){
            $("<p>").text("明天").appendTo(li);
        }else{
            $("<p>").text(week[date.getDay()]).appendTo(li);
        }
        $("<time>").text((date.getMonth()+1)+"/"+date.getDate()).appendTo(li);
        li.appendTo(dtFmlDateSel);
    }
    $("li",dtFmlDateSel).on("click",function(){
        if($(this).hasClass("selected")){
            return false;
        }else{
            //重新选择日期
            $(this).addClass("selected");
            selectedDay.removeClass("selected");
            selectedDay = $(this);
            var dateString = $(this).attr("date");
            applyFamilyData.interviewDate = dateString;
            dtFmlDateSpan.text(dateString);
            //清空时间已选项
            selectedTime = null;
            applyFamilyData.interviewTime = null;
            dtFmlTimeSpan.text('请选择');
            dtFmlTimeSel.empty();
            getInterviewTime(dateString);
        }
    });
    dtFmlTimeSel.empty();
    var dateString = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
    getInterviewTime(dateString);
}
/**
 * 获取当日视频认证时间段
 */
var getInterviewTime = function(dateString){
    var data = {
        interviewDate: dateString,
        type: 1
    }
    $.ajax({
        url: "/viptail/api/family/getInterviewSchedule",
        data: data,
        type: "GET",
        dataType: 'json',
        success: function(res){
            if(res.respCode==0){
                var results = res.results;
                var tr = null,j = 0;//表格行元素
                for(var i = 0; i < results.length; i++){
                    var cur = results[i];
                    var td = $("<td>").attr("id",cur.id).text(cur.interviewTime);
                    var curDate = Date.parse(cur.interviewDate+" "+cur.interviewTime.split("~")[1]+":00");//yyyy-mm-dd h24:mi:as
                    var now = (new Date()).getTime();
                    //判断不可选状态
                    if(now > curDate){
                        td.addClass("dated");
                    }else if(cur.surplus == 0){
                        td.addClass("full");
                    }
                    //表格三个一行
                    if(i%3 == 0){
                        tr = $("<tr>").attr("row",j++);
                        dtFmlTimeSel.append(tr);
                    }
                    tr.append(td);
                }
                $("td",dtFmlTimeSel).on("click",function(){
                    if(!$(this).hasClass("full") && !$(this).hasClass("dated")){
                        $(this).addClass("selected");
                        if(selectedTime!=null){
                            selectedTime.removeClass("selected");
                        }
                        selectedTime = $(this);
                        applyFamilyData.interviewTime = $(this).text();
                        dtFmlTimeSpan.text($(this).text());
                    }else if($(this).hasClass("selected")){
                        selectedTime = null;
                        applyFamilyData.interviewTime = null;
                    }
                });
            }
        }
    });
}
/**
 * 选择视频认证时间
 */
var interviewSelect = function(){
    dtFmlDateSel = $("#dtFmlDateSel",intrvwSelIframe.contents());//面试日期选择
    dtFmlTimeSel = $("#dtFmlTimeSel",intrvwTimeSelIframe.contents());//面试时间段选择
    if(selectedDay == null){
        displayInterviewDate();
    }
}
/**
 * 禁止页面滚动
 */
var move = function(e){
    e.preventDefault && e.preventDefault();
    e.returnValue = false;
    e.stopPropagation && e.stopPropagation();
    return false;
}
var keyFunc = function(e){
    if(37<=e.keyCode && e.keyCode<=40){
        return move(e);
    }
}
var stopScrolling = function(){
    document.documentElement.style.overflow = "hidden";
    document.body.style.overflow = "hidden";
    document.body.onkeydown = keyFunc;
    $("body").on("keydown",keyFunc);
}
/**
 * 恢复页面滚动
 */
var startScrolling = function(){
    document.documentElement.style.overflow = "auto";
    document.body.style.overflow = "auto";
    $("body").off("keydown",keyFunc);
}
/**
 * 手机号/QQ号输入期间检查（只允许输入数字）
 */
function check(e){
    var keyCode = e.keyCode || event.keyCode;
    if (keyCode >= 48 && keyCode <= 57) {
        event.returnValue = true;
    }else {
        event.returnValue = false;
    }
}
/**
 * 提示框
 */
var showMessageAlert = function(message){
    var mssAlert = $("#messageAlert");
    if(mssAlert.length==0 || mssAlert==undefined || mssAlert==null){
        mssAlert = $("<div>").attr("id","messageAlert")
            .addClass("message_alert");
        $("<p>").text(message)
            .css({width: message.length+"em"})
            .appendTo(mssAlert);
        $("body").append(mssAlert);
    }else{
        mssAlert.find("p").text(message)
            .css({width: message.length+"em"});
        mssAlert.show();
    }
    setTimeout(function(){
        mssAlert.hide();
    },1000);
}
/**
 * 加密方法
 * @param value
 * @returns {*}
 */
var code = function(value){
    if(value=="" || value==null){
        return "";
    }
    $.base64.utf8encode = true;
    if(value instanceof Object){
        value.jsonData = JSON.stringify(value.jsonData);
        value = JSON.stringify(value);
    }
    value = $.base64.encode(value);
    var middle = value.substring(1,3).split("").reverse().join("");
    var arr0 = value.charAt(0);
    var arr1 = value.substring(3,value.length);
    return $.base64.encode(arr0.concat(middle.concat(arr1)));
}
/**
 * JSON数据的参数分别加密
 * @param data
 * @returns {{}}
 */
var paramCoding = function(data){
    var codedData = {};
    $.each(data,function(key,value){
        if(key=='file'){
            codedData[key] = value;
        }else{
            codedData[key] = code(value);
        }
    });
    return codedData;
}
$(window).on("beforeunload",function(){
    return "是否退出申请页面？您所填写的内容将不会保存";
});